package com.example.demo.labor;


import org.springframework.util.StopWatch;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.UUID;

/**
 * Hello world!
 */
public class App {
    public static void call() throws UnsupportedEncodingException {
        System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog");
        System.setProperty("org.apache.commons.logging.simplelog.showdatetime", "true");
        System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.commons.httpclient", "stdout");


        String appid = "12011420190701400002";
        String appsecret = "883a412280214daa87c0fe81a557276c";
        //String method = "ProjectSubContractor.Add";
        //String data = "{\"ProjectSubSysno\":299809,\"bankInfos\":[],\"corpCode\":\"91320508MA215X6T41\",\"corpName\":\"苏州翀天智能化工程有限公司\",\"corpType\":\"001\",\"entryTime\":\"2023-04-12 00:00:00\",\"exitTime\":null,\"pmIDCardNumber\":\"\",\"pmIDCardType\":null,\"pmName\":null,\"pmPhone\":null,\"projectCode\":\"12011420190701400002\",\"SubContractorSysNo\":67975,\"Status\":1,\"EditDate\":\"2023-04-12+11:00:36\"}";
        String method = "ProjectWorker.Add";
        String data = "{\"projectCode\":\"12011420190701400002\",\"corpCode\":\"913204041371823866\",\"corpName\":\"江苏烨瑞建设工程有限公司\",\"teamSysNo\":1500570945,\"teamName\":\"园林\",\"workerList\":[{\"teamSysNo\":0,\"workerName\":\"朱宝青\",\"isTeamLeader\":0,\"idCardType\":\"01\",\"idCardNumber\":\"fhm623kwELKYmdV5JPhdgKhNuIRoQOlmSuDnru/sK7Q=\",\"workType\":\"1000\",\"workRole\":\"20\",\"issueCardDate\":\"2023-04-11\",\"issueCardPic\":\"https://lwres.yzw.cn/worker-avatar/Original/2023/0411/1af6de6d-8a78-4f86-b2c6-52ffbe96c445.jpeg\",\"cardNumber\":\"1000001\",\"payRollBankCardNumber\":null,\"payRollBankName\":null,\"bankLinkNumber\":null,\"payRollTopBankCode\":null,\"hasBuyInsurance\":0,\"nation\":\"汉\",\"gender\":\"0\",\"address\":\"江苏省海安县雅周镇周机村二十四组8号\",\"headImage\":\"https://lwres.yzw.cn/worker-avatar/Original/2023/0411/6423d6d5-d685-4597-bb69-203cea89ac16.jpeg\",\"politicsType\":\"13\",\"joinedTime\":null,\"cellPhone\":\"18795455799\",\"cultureLevelType\":\"01\",\"specialty\":null,\"hasBadMedicalHistory\":null,\"urgentLinkMan\":null,\"urgentLinkManPhone\":null,\"workDate\":null,\"maritalStatus\":null,\"grantOrg\":\"海安县公安局\",\"positiveIDCardImage\":null,\"negativeIDCardImage\":null,\"startDate\":null,\"expiryDate\":null,\"manageType\":null}]}";

        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        System.out.println("start to prepare ");
        push(appid, appsecret, method, data);
        stopWatch.stop();
        System.out.println("ended, total elapsed seconds " + stopWatch.getTotalTimeSeconds());

//        Scanner scan = new Scanner(System.in);
//        System.out.println("PLEASE ENTER THE【URL】:");
//        url = scan.nextLine();
//        if (StringUtils.isEmpty(url)) {
//            System.out.println("请求URL地址不能为空");
//        }
//
//        System.out.println("PLEASE ENTER THE 【APPID】:");
//        appid = scan.nextLine();
//
//        System.out.println("PLEASE ENTER THE 【APPSECRET】:");
//        appsecret = scan.nextLine();
//
//        System.out.println("PLEASE ENTER THE 【METHOD】:");
//        method = scan.nextLine();
//
//        System.out.println("PLEASE ENTER THE 【VERSION】:(IF EMPTY:1.0)");
//        String tempVersion = scan.nextLine();
//        version = StringUtils.isEmpty(tempVersion) ? "1.0" : tempVersion;
//
//
//        System.out.println("PLEASE ENTER THE 【DATA】:");
//        data = acceptmultiLineChars2(scan).replaceAll("\"","\\\"");
//        if (data.length() > 2) {
//            data = data.substring(0,data.length() - 2);
//        }

    }

    public static void push(String appid,
                            String appsecret,
                            String method,
                            String data) {
        //String url = "https://111.164.113.170:8081/openapi/open.api";
        String url = "https://111.164.113.170:8081/openapi/open.api";
        String version = "1.0";

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");

        String sortString = "appid=" + appid;
        String guid = UUID.randomUUID().toString().replace("-", "");
        String timestamp = sdf.format(new Date());

        sortString += "&data=" + data;
        sortString += "&format=json";
        sortString += "&method=" + method;
        sortString += "&nonce=" + guid;
        sortString += "&timestamp=" + timestamp;
        sortString += "&version=" + version;
        sortString += "&appsecret=" + appsecret;

        String sign = EncriptionHelper.getSHA256StrJava(sortString.toLowerCase());
        System.out.println(String.format("加密后签名串为：%s", sign));

        BaseRequest request = new BaseRequest() {
        };
        Map<String, String> dataMap = new HashMap<>();
        dataMap.put("appid", appid);
        dataMap.put("data", data);


        dataMap.put("format", "json");
        dataMap.put("method", method);
        dataMap.put("nonce", guid);
        dataMap.put("timestamp", timestamp);
        dataMap.put("version", version);
        dataMap.put("sign", sign);
        try {
            StopWatch stopWatch = new StopWatch();
            stopWatch.start();
            System.out.println("start to call service");
            String res = request.postData(url, null, dataMap);
            stopWatch.stop();
            System.out.println("call service end, elapsed seconds " + stopWatch.getTotalTimeSeconds());

            dataMap.put("appsecret", appsecret);
            WriteLogInfo(dataMap);
            System.out.println(String.format("调用结果：%s", res));
        } catch (Exception ex) {
            String errorMsg = "";
            if (ex.getMessage().contains("ClientProtocolException")) {
                errorMsg = "异常：输入的URL无效";
            } else if (ex.getMessage().contains("UnknownHostException") || ex.getMessage().contains("unreachable")) {
                errorMsg = "异常：输入的URL不正确";
            }
            System.out.println(errorMsg);
        }
    }


    private static void WriteLogInfo(Map<String, String> map) {
        String paraString = "";
        StringBuilder sb = new StringBuilder();
        sb.append("appid=" + map.get("appid") + "&");
        sb.append("data=" + map.get("data") + "&");
        sb.append("format=" + map.get("format") + "&");
        sb.append("method=" + map.get("method") + "&");
        sb.append("nonce=" + map.get("nonce") + "&");
        sb.append("timestamp=" + map.get("timestamp") + "&");
        sb.append("version=" + map.get("version") + "&");
        sb.append("appsecret=" + map.get("appsecret") + "&");
        sb.append("sign=" + map.get("sign"));
        paraString = sb.toString();
        paraString = paraString.replace("\r", "").replace("\n", "").replace(" ", "");
        System.out.println(String.format("请求FormData:%s \r\n", paraString));
    }

    private static String acceptmultiLineChars2(Scanner sc) {
        ArrayList<String> ns = new ArrayList<>();
        do {
            String str = sc.nextLine();
            if (str.equals("")) {
                break;
            }
            ns.add(str);
        } while (true);
        StringBuilder sb = new StringBuilder();
        if (ns.size() > 0) {
            ns.forEach(item -> sb.append(item + "\r\n"));
        }
        return sb.toString();
    }
}
